package com.shopping.config;

import com.shopping.security.JwtAuthenticationFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Slf4j
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter; // 注入自定义的 JWT 过滤器

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf(csrf -> csrf.disable()) // 禁用 CSRF 保护
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/api/login/**").permitAll() // 允许所有用户访问登录接口
                        .requestMatchers("/api/register/**").permitAll() // 允许所有用户访问注册接口
                        .requestMatchers("/images/**").permitAll() // 允许所有用户访问图片接口
//                        .requestMatchers("/api/upload/**").permitAll()
//                        .requestMatchers("/api/home/**").permitAll()// 测试用
//                        .requestMatchers("/api/cart/**").permitAll()// 测试用
//                        .requestMatchers("/api/user/**").permitAll()
//                        .requestMatchers("/api/adminhome/**").permitAll()
                        .requestMatchers("/api/home/**").hasAnyAuthority("CUSTOMER", "ADMIN") // 只有身份为 CUSTOMER 和ADMIN 的用户可以访问
                        .requestMatchers("/api/cart/**").hasAnyAuthority("CUSTOMER", "ADMIN")
                        .requestMatchers("/api/user/**").hasAnyAuthority("CUSTOMER", "ADMIN")
                        .requestMatchers("/api/adminhome/**").hasAuthority("ADMIN") // 只有身份为 ADMIN 的用户可以访问 /adminhome
                        .anyRequest().authenticated() // 其他请求需要认证
                )
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); // 添加 JWT 过滤器

        return http.build(); // 构建 SecurityFilterChain
    }
}